<?php
        class ApiCenter_SalesApi_Helper_Data extends Mage_Core_Helper_Data
        {
            protected $shippingForWeight=array(
                "14"=>"30",
                "16"=>"2"
            );
            
            const SFCODE="sf";
           
            const  DEFAULT_WIDTH=        "100";
            
            const  DEFAULT_HEIGHT=        "100";
            
            const  NOIMAGE ="";
            /**
             * 查询订单的item信息  并过滤掉不能确认的订单item
             * $orderId   have a order item must belong to vendor
             * $vendor_id  ID
             * return  bloor| array
             */
            public  function _businessFilterOrder($orderId,$vendor_id){
                $item_collection =  Mage::getResourceModel("sales/order_item_collection");
                $item_collection->addFieldToFilter("main_table.vendor_id",$vendor_id);
                $item_collection->addFieldToFilter("main_table.parent_item_id",array('null' => ''));
                $item_collection->addFieldToFilter("main_table.order_id",$orderId);   
                $item_collection->addFieldToFilter("d.status","payment_success");
                $item_collection->addFieldToSelect("*");
                $item_collection->getSelect()
                ->joinLeft(array('d' => 'sales_flat_order'),
                    'd.entity_id = main_table.order_id',
                    array(
                        "increment_id"=>"d.increment_id",
                    ))
                    ->joinLeft(array('f' => 'tb_sales_flat_order'),
                        'LEFT(f.increment_id,9) = d.increment_id AND (`main_table`.`vendor_id` = `f`.`vendor_id`)',
                        array(
                            "fincrement_id"=>"f.increment_id",
                        ))  
                 //         ->group("main_table.order_id")
                            ->where(" f.increment_id is null");
                if(!$itemData = $item_collection->getData()){      
                    return false;
                }    
                $items =false;
                //如果有一件产品以上
                if(count($itemData>1)){
                    foreach ($itemData as $k=>$v){
                        
                        //只要有一件商品不在顺丰仓  即可确认订单。
                          $collection = Mage::getModel('catalog/product')->getCollection()
                             ->addAttributeToSelect('*')
                            ->addAttributeToFilter('vendor_id',$vendor_id)
                            ->addAttributeToFilter('entity_id',$v['product_id']); 
                                if(empty($collection->getData())){
                                    return "商品已经删除";
                                }
                                foreach ($collection as $product){
                                    $_product=$product;
                                }
                        if($_product->getCommonWarehouseCode()!=self::SFCODE){
                            $items[$k]=$v;
                            $items[$k]['product_info']['id']=$_product->getEntityId();
                            $items[$k]['product_info']['name']=$_product->getName();
                            $items[$k]['product_info']['length']=$_product->getCommonPackageLength();
                            $items[$k]['product_info']['width']=$_product->getCommonPackageWidth();
                            $items[$k]['product_info']['height']=$_product->getCommonPackageHeight();
                            $items[$k]['product_info']['warehousecode']=$_product->getCommonWarehouseCode();
                            $items[$k]['product_info']['weight']=$_product->getCommonWeight();
                            $items[$k]['product_info']['shipping_type_name']=$_product->getResource()->getAttribute('common_shipping_type')
                           ->setStoreId(0)->getFrontend()->getValue($_product);
                            $items[$k]['product_info']['shipping_type_id']=$_product->getCommonShippingType();
                            $items[$k]['product_info']['default_img_url'] = $this->_loadImgUrl($v['sku']);
                            $items[$k]['product_info']['is_mail'] =$_product->getCommonShippingType()==14?1:0;
                            $items[$k]['product_info']['weight_limit'] =$this->shippingForWeight[$_product->getCommonShippingType()];
                       
                        }
                    }
                    return $items;
                }else{
                    $collection = Mage::getModel('catalog/product')->getCollection()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('vendor_id',$vendor_id)
                    ->addAttributeToFilter('entity_id',$itemData[0]['product_id']); 
                                foreach ($collection as $product){
                                    $_product=$product;
                                }
                        if($_product->getCommonWarehouseCode()!=self::SFCODE){
                            $items[1]['product_info']['id']=$_product->getId();
                            $items[1]['product_info']['name']=$_product->getName();
                            $items[1]['product_info']['length']=$_product->getCommonPackageLength();
                            $items[1]['product_info']['width']=$_product->getCommonPackageWidth();
                            $items[1]['product_info']['hegiht']=$_product->getCommonPackageHeight();
                            $items[1]['product_info']['warehousecode']=$_product->getCommonWarehouseCode();
                            $items[1]['product_info']['weight']=$_product->getCommonWeight();
                            $items[1]['product_info']['shipping_type_name']=$_product->getResource()->getAttribute('common_shipping_type')
                            ->setStoreId(0)->getFrontend()->getValue($_product);
                            $items[1]['product_info']['shipping_type_id']=$_product->getCommonShippingType();
                            $items[1]['product_info']['default_img_url'] = $this->_loadImgUrl($itemData[0]["sku"]);
                            $items[1]['product_info']['is_mail'] =$_product->getCommonShippingType()==14?1:0;
                            $items[1]['product_info']['weight_limit'] =$this->shippingForWeight[$_product->getCommonShippingType()];
                            return $items[1]=$itemData;
                        }else{
                            
                            return false;
                        }
                 }              
            }
            
            /*获取item 产品的图片信息*/
            public  function _loadImgUrl($sku){
                $w = self::DEFAULT_WIDTH;
                $h = self::DEFAULT_HEIGHT;
                $imageUrl ="";
                $product  = Mage::getModel('catalog/product')->setStoreId(0)->loadByAttribute('sku',$sku);
                if(!$product) return self::NOIMAGE;
                $configurable_ids  = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
                if(count($configurable_ids) > 0){
                    $productConfig = Mage::getModel('catalog/product')->setStoreId(0)->load($configurable_ids[0]);
                    $colorText = $product->getResource()->getAttribute('common_color')->setStoreId(0)->getFrontend()->getValue($product);
                    $_img = $productConfig->getMediaGalleryImages()->getItemByColumnValue('label',$colorText);
                    if(!empty($colorText) && !empty($_img)){
                        $imageUrl = (string)Mage::helper('catalog/image')->init($productConfig, 'thumbnail', $_img->getFile())->resize($w, $h);
                    }else{
                        if($productConfig->getImage() != 'no_selection'){
                            $imageUrl = (string)Mage::helper('catalog/image')->init($product, 'thumbnail')->resize($w, $h);
                        }
                    }
                     
                }else{
                    if($product->getImage() != 'no_selection')
                    {
                        $imageUrl   = (string)Mage::helper('catalog/image')->init($product, 'thumbnail')->resize($w, $h);
                    }
                }
                return $imageUrl;
            }
            /**
             *  用于验证分订单数据格式 并组装数据
             *  $data   数据
             *  $odrderid 总订单id
             *  $vendorid 商家id
             * @return boolean|array
             * */
            public function validateConfirmOrder($data,$orderid,$vendorid){
                $check_info=array();

                if(!is_array($data)){
                    throw new Exception("订单数据无效");
                }
                if(!$this->_businessFilterOrder($orderid, $vendorid)){
                    throw new Exception("该订单已经确认完毕!");
                }
                $link = "";
                $model = Mage::getModel("sales/order");
                $item_model = Mage::getModel("sales/order_item");
                $inCrementId= $model->load($orderid)->getIncrementId();
                
                $orderTradeNo = $this->getOrderTradeNo($orderid);
               foreach ($data as $k=>$val){
                       
                       foreach($val['items'] as $p=>$item){      
                           $Itemweight=0;
                           $link['items']= $item;
                           $link['order_id'] =$val['order_id'];
                           $link['vendor_id'] =$val['vendor_id'];
                           $link['shipping_type'] =$val['shipping_type'];
                           $link['trade_no']=$orderTradeNo;
                           $sendData[]=$link;
                           $sendData[$p]['trade_no']=$orderTradeNo;
                                foreach ($item as $_item ){
                                   $Itemweight+=$_item['sub_weight']*$_item['qty'];
                                   $check_info[$_item['sku']]['qty']=$_item['qty']+@$check_info[$_item['sku']]['qty'];
                                   $check_info[$_item['sku']]['item']=$_item['item_id'];
                                }
            }
            
                       if($this->shippingForWeight[$val['shipping_type']]<$Itemweight){
                           throw new Exception("商品已经超重！!");
                       }
               }
               //验证商家的商品数量是否已经分配完毕
                foreach ($check_info as $t=>$b){
                    $skuQty = $item_model->load($b["item"],"item_id")->getQtyOrdered();
                    if($skuQty!=$b['qty']){
                           throw new Exception( sprintf('sku "%s" 的商品没有被分单完毕.', $t));
                        }
                }
        
               try {
    
                       $sendDataXml =   Mage::helper('saleorderservice')->pushOrderInfo($sendData);

                   
                   } catch (Exception $e) {
                   Mage::log("推送确认订单接口错误",1,"api.log");
               }
               
                return $sendDataXml;
            }
            public function querySkuQtyByIncrementId($incrementId,$vendorId){
                $collection = Mage::getResourceModel("salesapi/order_collection")
                ->addFieldToFilter('main_table.vendor_id', $vendorId)
                ->addFieldToFilter('main_table.increment_id', array('like'=>'%'.$incrementId.'%'))
                ->addFieldToSelect('entity_id');
                $collection->getSelect()
                ->joinLeft(array("tsfoi"=>"sales_flat_order_item"),
                    "main_table.entity_id = tsfoi.order_id",
                    array('tsfoi.sku','tsfoi.qty_ordered')
                    )
                    ->columns(
                        array('qty_ordered' => new Zend_Db_Expr('sum(tsfoi.qty_ordered)')
                        ))
                        ->group('tsfoi.sku');
                        return $collection->getData();
            }
            public  function getOrderTradeNo($orderId){
                $order = Mage::getModel('sales/order')->load($orderId, 'entity_id');
                $historys = $order->getStatusHistoryCollection();
                foreach($historys as $history){
                    if($history->getStatus() == 'payment_success'){
                        if(!$comment = $history->getComment()){
                            return null;
                        }
                        $keyword = 'tradeNo:';
                        $keyword1 = 'payment_id:';
                        if(strstr($comment, $keyword)){
                            $comment = rtrim(substr($comment, strpos($comment, $keyword)+strlen($keyword), 22), ' ');
                            return $comment;
                        }elseif(strstr($comment, $keyword1)){
                            $comment = rtrim(substr($comment, strpos($comment, $keyword1)+strlen($keyword1), 21), ' ');
                            return $comment;
                        }
                    }
                }
                return false;
            }
            
            
            //为筛选订单添加条件
            public function _applyToCollectionFilter(Varien_Data_Collection_Db $collection,$filter)
            {
                if (!$filter) {
                    return $this;
                }
                if (!is_array($filter)) {
                    $this->_critical(self::RESOURCE_COLLECTION_FILTERING_ERROR);
                }
                if (method_exists($collection, 'addAttributeToFilter')) {
                    $methodName = 'addAttributeToFilter';
                } elseif (method_exists($collection, 'addFieldToFilter')) {
                    $methodName = 'addFieldToFilter';
                } else {
                    return $this;
                }
                $allowedAttributes = $this->getFilter()->getAllowedAttributes(self::OPERATION_ATTRIBUTE_READ);
                 
                foreach ($filter as $filterEntry) {
                    if (!is_array($filterEntry)
                        || !array_key_exists('attribute', $filterEntry)
                        || !in_array($filterEntry['attribute'], $allowedAttributes)
                    ) {
                        $this->_critical(self::RESOURCE_COLLECTION_FILTERING_ERROR);
                    }
                    $attributeCode = $filterEntry['attribute'];
                     
                    unset($filterEntry['attribute']);
                     
                    try {
                        $collection->$methodName($attributeCode, $filterEntry);
                    } catch(Exception $e) {
                        $this->_critical(self::RESOURCE_COLLECTION_FILTERING_ERROR);
                    }
                }
                return $this;
            }
            
            
        }
        
        
        
        